/*
 * Galaxium Messenger
 * Copyright (C) 2007 Ben Motmans <ben.motmans@gmail.com>
 * Copyright (C) 2007 Philippe Durand <draekz@gmail.com>
 * Copyright (C) 2007 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;

using Gdk;
using Gtk;
using Glade;

using Anculus.Core;

using Galaxium.Core;
using Galaxium.Gui;
using Galaxium.Gui.GtkGui;
using Galaxium.Protocol;

namespace Galaxium.Client.GtkGui
{
	public class EmoticonPreferenceWidget: IPreferenceWidget<Widget>
	{
		[Widget("vbSets")] VBox _vbSets;
		[Widget("ivEmoticons")] IconView _ivEmoticons;
		[Widget("lblAuthor")] Label _lblAuthor;
		[Widget("lblDescription")] Label _lblDescription;
		[Widget("tvCustom")] TreeView _tvCustom;
		[Widget("btnAdd")] ToolButton _btnAdd;
		[Widget("btnRemove")] ToolButton _btnRemove;
		
		Widget _nativeWidget;
		Widget _parentLayoutWidget;
		ImageComboBox<IEmoticonSet> _cbSets;
		IEmoticonSet _noneSet;
		ListStore _tvCustomStore;
		ListStore _accountsStore;
		ListStore _contactsStore;
		
		public void Initialize ()
		{
			_nativeWidget = GladeUtility.ExtractWidget<Widget> (GladeUtility.GetGladeResourceStream (typeof (GtkPreferenceWidget).Assembly, "EmoticonPreferenceWidget.glade"), "widget", this);
			
			// Emoticon Sets
			
			_cbSets = new ImageComboBox<IEmoticonSet>(new ImageComboTextLookup<IEmoticonSet>(SetTextLookup), new ImageComboPixbufLookup<IEmoticonSet>(SetImageLookup));
			_vbSets.PackStart(_cbSets, false, true, 0);
			
			_noneSet = new BaseEmoticonSet("None", string.Empty, string.Empty);
			_cbSets.Append(_noneSet);
			
			foreach (IEmoticonSet emotSet in EmoticonUtility.Sets)
				_cbSets.Append(emotSet);
			
			_cbSets.Changed += SetChanged;
			
			if (EmoticonUtility.ActiveSet != null)
				_cbSets.Select(EmoticonUtility.ActiveSet);
			else
				_cbSets.Select(_noneSet);
			
			// Custom Emoticons
			
			_tvCustom.AppendColumn("Image", new CellRendererPixbuf(), new TreeCellDataFunc(RenderCustomImage));
			_tvCustom.AppendColumn("Equivalents", new CellRendererText(), new TreeCellDataFunc(RenderCustomEquivalents));
			_tvCustom.AppendColumn("Account", new CellRendererCombo(), new TreeCellDataFunc(RenderCustomAccount));
			_tvCustom.AppendColumn("Contact", new CellRendererCombo(), new TreeCellDataFunc(RenderCustomContact));
			
			((CellRendererText)_tvCustom.Columns[1].CellRenderers[0]).Editable = true;
			((CellRendererText)_tvCustom.Columns[1].CellRenderers[0]).Edited += CustomEquivalentsEdited;
			
			((CellRendererCombo)_tvCustom.Columns[2].CellRenderers[0]).Editable = true;
			((CellRendererCombo)_tvCustom.Columns[2].CellRenderers[0]).Edited += CustomAccountEdited;
			
			((CellRendererCombo)_tvCustom.Columns[3].CellRenderers[0]).Editable = true;
			((CellRendererCombo)_tvCustom.Columns[3].CellRenderers[0]).Edited += CustomContactEdited;
			
			_tvCustomStore = new ListStore(typeof(CustomEmoticonInfo));
			_tvCustom.Model = _tvCustomStore;
			
			_tvCustom.Selection.Changed += tvCustomSelectionChanged;
			
			// Setup Accounts Combo
			
			_accountsStore = new ListStore(typeof(string));
			_accountsStore.AppendValues("All");
			
			foreach (IAccount account in AccountUtility.Accounts)
				_accountsStore.AppendValues(account.UniqueIdentifier);
			
			((CellRendererCombo)_tvCustom.Columns[2].CellRenderers[0]).Model = _accountsStore;
			((CellRendererCombo)_tvCustom.Columns[2].CellRenderers[0]).TextColumn = 0;
			((CellRendererCombo)_tvCustom.Columns[2].CellRenderers[0]).HasEntry = false;
			
			// Setup Contacts Combo
			
			_contactsStore = new ListStore(typeof(string));
			_contactsStore.AppendValues("All");

			((CellRendererCombo)_tvCustom.Columns[3].CellRenderers[0]).Model = _contactsStore;
			((CellRendererCombo)_tvCustom.Columns[3].CellRenderers[0]).TextColumn = 0;
			((CellRendererCombo)_tvCustom.Columns[3].CellRenderers[0]).HasEntry = false;
			
			// Setup Emoticon Store
			
			foreach (CustomEmoticonInfo info in EmoticonUtility.Custom)
				_tvCustomStore.AppendValues(info);
			
			_nativeWidget.ShowAll ();
		}
		
		string SetTextLookup (IEmoticonSet item)
		{
			return item.Name;
		}

		Gdk.Pixbuf SetImageLookup (IEmoticonSet item)
		{
			return IconUtility.GetIcon ("galaxium-preferences-themes", IconSizes.Small);
		}
		
		void SetChanged(object sender, EventArgs args)
		{
			IEmoticonSet emotSet = _cbSets.GetSelectedItem();
			
			EmoticonUtility.ActiveSet = emotSet == _noneSet ? null : emotSet;
		
			_lblAuthor.Text = emotSet.Creator;
			_lblDescription.Text = emotSet.Description;
			
			_ivEmoticons.Model = null;
			
			if (emotSet != null)
			{
				ListStore store = new ListStore(new Type[] { typeof(string), typeof(Gdk.Pixbuf) });
				
				foreach (IEmoticon emot in emotSet.Emoticons)
					store.AppendValues(new object[] { emot.Equivalents[0], new Gdk.Pixbuf(emot.Filename) });
				
				_ivEmoticons.Model = store;
				_ivEmoticons.TextColumn = 0;
				_ivEmoticons.PixbufColumn = 1;
				_ivEmoticons.ShowAll();
			}
		}
		
		void tvCustomSelectionChanged(object sender, EventArgs args)
		{
			_btnRemove.Sensitive = true;
		}
		
		void RenderCustomImage(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			CustomEmoticonInfo info = (CustomEmoticonInfo)model.GetValue(iter, 0);
			if(File.Exists(info.Emoticon.Filename))
				(cell as CellRendererPixbuf).Pixbuf = new Pixbuf(info.Emoticon.Filename);
			else
				Log.Warn ("Custom emoticon file missing: "+info.Emoticon.Filename);
		}
		
		void RenderCustomEquivalents(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			CustomEmoticonInfo info = (CustomEmoticonInfo)model.GetValue(iter, 0);
			
			string equivalentstr = string.Empty;
			
			foreach (string equivalent in info.Emoticon.Equivalents)
				equivalentstr += equivalent + " ";
			
			(cell as CellRendererText).Text = equivalentstr.Trim();
		}
		
		void RenderCustomAccount(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			CustomEmoticonInfo info = (CustomEmoticonInfo)model.GetValue(iter, 0);
			(cell as CellRendererCombo).Text = info.AllowedAccount == "*" ? "All" : info.AllowedAccount;
		}
		
		void RenderCustomContact(TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			CustomEmoticonInfo info = (CustomEmoticonInfo)model.GetValue(iter, 0);
			(cell as CellRendererCombo).Text = info.AllowedDestination == "*" ? "All" : info.AllowedDestination;
		}
		
		void btnAddClicked(object sender, EventArgs args)
		{
			FileChooserDialog dialog = new ImageFileChooserDialog((Gtk.Window)_nativeWidget.Toplevel);			
			dialog.SetCurrentFolder(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
			
			if (dialog.Run () == (int)ResponseType.Accept)
				_tvCustomStore.AppendValues(EmoticonUtility.AddCustom(dialog.Filename));
			
			dialog.Destroy();
		}
		
		void btnRemoveClicked(object sender, EventArgs args)
		{
			TreeIter iter;
			_tvCustom.Selection.GetSelected(out iter);
			
			if (iter.Equals(TreeIter.Zero))
				return;
			
			CustomEmoticonInfo info = (CustomEmoticonInfo)_tvCustomStore.GetValue(iter, 0);
			
			EmoticonUtility.RemoveCustom(info);
			
			_tvCustomStore.Remove(ref iter);
		}
		
		void CustomEquivalentsEdited(object sender, EditedArgs args)
		{
			TreeIter iter;
			_tvCustomStore.GetIter(out iter, new TreePath(args.Path));

			CustomEmoticonInfo info = (CustomEmoticonInfo)_tvCustomStore.GetValue(iter, 0);
			info.SetEquivalents(args.NewText);
			
			_tvCustom.ColumnsAutosize();
		}
		
		void CustomAccountEdited(object sender, EditedArgs args)
		{
			TreeIter iter;
			_tvCustomStore.GetIter(out iter, new TreePath(args.Path));

			CustomEmoticonInfo info = (CustomEmoticonInfo)_tvCustomStore.GetValue(iter, 0);
			info.AllowedAccount = args.NewText == "All" ? "*" : args.NewText;
			
			_tvCustom.ColumnsAutosize();
		}
		
		void CustomContactEdited(object sender, EditedArgs args)
		{
			TreeIter iter;
			_tvCustomStore.GetIter(out iter, new TreePath(args.Path));

			CustomEmoticonInfo info = (CustomEmoticonInfo)_tvCustomStore.GetValue(iter, 0);
			info.AllowedDestination = args.NewText == "All" ? "*" : args.NewText;
			
			_tvCustom.ColumnsAutosize();
		}
		
		public Widget NativeWidget
		{
			get { return _nativeWidget; }
		}
	}
}
